package net.dreamlu.config;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.dreamlu.controller.BlogController;
import net.dreamlu.controller.IndexController;
import net.dreamlu.controller.LifeController;
import net.dreamlu.controller.TestController;
import net.dreamlu.controller.admin.AdminBlogController;
import net.dreamlu.controller.admin.AdminController;
import net.dreamlu.controller.admin.AdminLinksController;
import net.dreamlu.controller.admin.AdminOptionsController;
import net.dreamlu.controller.admin.AdminTagsController;
import net.dreamlu.controller.admin.AdminUserController;
import net.dreamlu.controller.admin.UeditorController;
import net.dreamlu.controller.admin.WeChatController;
import net.dreamlu.controller.api.BaiduLogin;
import net.dreamlu.controller.api.OscLogin;
import net.dreamlu.controller.api.QQLogin;
import net.dreamlu.controller.api.SinaLogin;
import net.dreamlu.controller.api.WeChat;
import net.dreamlu.handler.HttpCacheHandler;
import net.dreamlu.handler.QRcodeHandler;
import net.dreamlu.handler.SessionIdHandler;
import net.dreamlu.handler.SiteMapHandler;
import net.dreamlu.helpers.JadeHelper;
import net.dreamlu.interceptor.CookieLoginInterceptor;
import net.dreamlu.interceptor.InstallInterceptor;
import net.dreamlu.interceptor.OptionsInterceptor;
import net.dreamlu.interceptor.SessionInterceptor;
import net.dreamlu.model.Blog;
import net.dreamlu.model.BlogTag;
import net.dreamlu.model.Links;
import net.dreamlu.model.MailVerify;
import net.dreamlu.model.Options;
import net.dreamlu.model.Tags;
import net.dreamlu.model.User;
import net.dreamlu.model.WBLogin;
import net.dreamlu.model.WxLeaveMsg;
import net.dreamlu.model.WxRule;
import net.dreamlu.utils.ConfigUtil;

import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.wall.WallFilter;
import com.jfinal.config.Constants;
import com.jfinal.config.Handlers;
import com.jfinal.config.Interceptors;
import com.jfinal.config.JFinalConfig;
import com.jfinal.config.Plugins;
import com.jfinal.config.Routes;
import com.jfinal.core.JFinal;
import com.jfinal.ext.handler.RenderingTimeHandler;
import com.jfinal.ext.plugin.memcache.MCachePlugin;
import com.jfinal.ext.render.JadeRender;
import com.jfinal.ext.render.JadeRenderFactory;
import com.jfinal.kit.StringKit;
import com.jfinal.log.Logger;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.CaseInsensitiveContainerFactory;
import com.jfinal.plugin.c3p0.C3p0Plugin;
import com.jfinal.plugin.druid.DruidPlugin;
import com.jfinal.plugin.druid.DruidStatViewHandler;
import com.jfinal.plugin.druid.IDruidStatViewAuth;
import com.jfinal.render.ViewType;

import de.neuland.jade4j.JadeConfiguration;

/**
 * 项目主要配置部分
 * 
 * @author L.cm email: 596392912@qq.com site: http://www.dreamlu.net
 * @date 2013-5-29 下午9:12:23
 */
public class JFWebConfig extends JFinalConfig {
	protected final Logger logger = Logger.getLogger(getClass());

	private boolean isLocal = isDevMode();

	/**
	 * 常量配置
	 */
	@Override
	public void configConstant(Constants me) {
		// 加载配置文件 静态到hashmap中
		ConfigUtil.loadConfig(loadPropertyFile("config.properties"));
		if (isLocal) {
			me.setDevMode(true);
		}
		// 设置jade模板
		me.setViewType(ViewType.OTHER);
		me.setMainRenderFactory(new JadeRenderFactory());
		// 添加jade标签
		JadeConfiguration config = JadeRender.getConfiguration();
		Map<String, Object> defaults = new HashMap<String, Object>();
		defaults.put("jTag", new JadeHelper());
		config.setSharedVariables(defaults);
		// jade end
		me.setBaseViewPath("/WEB-INF/pages");
		me.setError404View("/WEB-INF/pages/error/404.jade");
		me.setError500View("/WEB-INF/pages/error/500.jade");
	}

	/**
	 * 路由配置
	 */
	@Override
	public void configRoute(Routes me) {
		me.add("/", IndexController.class);
		me.add("/blog", BlogController.class, "/");
		me.add("/life", LifeController.class, "/life");
		// 第三方登录
		me.add("/api/qq", QQLogin.class, "/admin");
		me.add("/api/sina", SinaLogin.class, "/admin");
		me.add("/api/baidu", BaiduLogin.class, "/admin");
		me.add("/api/osc", OscLogin.class, "/admin");
		me.add("/api/wechat", WeChat.class);
		// 后台管理
		me.add("/admin", AdminController.class, "/admin");
		me.add("/admin/blog", AdminBlogController.class, "/admin/blog");
		me.add("/admin/tags", AdminTagsController.class, "/admin/tags");
		me.add("/admin/user", AdminUserController.class, "/admin/user");
		me.add("/admin/options", AdminOptionsController.class, "/admin");
		me.add("/admin/links", AdminLinksController.class, "/admin/links");
		me.add("/admin/wechat", WeChatController.class, "/admin/wechat");
		me.add("/ueditor", UeditorController.class);
		// 功能性测试
		me.add("/test", TestController.class);
	}

	/**
	 * 全局拦截器
	 */
	@Override
	public void configInterceptor(Interceptors me) {
		me.add(new InstallInterceptor());
		me.add(new CookieLoginInterceptor());
		me.add(new SessionInterceptor());
		me.add(new OptionsInterceptor());
	}

	/**
	 * 配置处理器
	 */
	@Override
	public void configHandler(Handlers me) {
		me.add(new RenderingTimeHandler());
		me.add(new SessionIdHandler());
		me.add(new SiteMapHandler());
		me.add(new QRcodeHandler());
		me.add(new HttpCacheHandler());
		// Druid监控
		DruidStatViewHandler druidViewHandler = new DruidStatViewHandler(	"/admin/druid",
																			new IDruidStatViewAuth() {
																				public boolean isPermitted(HttpServletRequest request) {
																					return true;
																				}
																			});
		me.add(druidViewHandler);
	}

	/**
	 * 配置插件
	 */
	@Override
	public void configPlugin(Plugins me) {
		// 配置数据源
		DruidPlugin dp = null;
//		C3p0Plugin dp =null;
		String jdbcUrl = "";
		String user = "";
		String password = "";

		if (isLocal) {
			jdbcUrl = getProperty("dev.jdbcUrl");
			user = getProperty("dev.user");
			password = getProperty("dev.password");
		} else {
			jdbcUrl = getProperty("db.jdbcUrl");
			user = getProperty("db.user");
			password = getProperty("db.password");
		}

//		jdbcUrl="jdbc:mysql://sqld.duapp.com:4050/OrYdcPZInFucKVDDtWQJ";
//		user="PcNqNT3BW8tKqoHyuBYI0nE2";
//		password="dMhBzmpxt9nSGRquyICAzIjIHwBGDsIT";
			
		if (logger.isErrorEnabled()) {
			logger.error("jdbc message:[" + jdbcUrl + "]\t[" + user + "]\t[" + password + "]");
		}
//		  dp =new C3p0Plugin(jdbcUrl, user, password);
		
		dp = new DruidPlugin(jdbcUrl, user, password);
		dp.setTestWhileIdle(true).setTestOnBorrow(true).setTestOnReturn(true);
		dp.addFilter(new StatFilter());
		WallFilter wall = new WallFilter();
		wall.setDbType("mysql");
		dp.addFilter(wall);
		me.add(dp);
		// 配置ActiveRecord插件
		ActiveRecordPlugin arp = new ActiveRecordPlugin(dp).setShowSql(true);
		arp.setContainerFactory(new CaseInsensitiveContainerFactory(false));
		me.add(arp);
		// 添加表匹配
		arp.addMapping(User.TABLE_NAME, User.class);
		arp.addMapping(Blog.TABLE_NAME, Blog.class);
		arp.addMapping(BlogTag.TABLE_NAME, BlogTag.class);
		arp.addMapping(WBLogin.TABLE_NAME, WBLogin.class);
		arp.addMapping(Options.TABLE_NAME, Options.class);
		arp.addMapping(Links.TABLE_NAME, Links.class);
		arp.addMapping(MailVerify.TABLE_NAME, MailVerify.class);
		arp.addMapping(WxRule.TABLE_NAME, WxRule.class);
		arp.addMapping(WxLeaveMsg.TABLE_NAME, WxLeaveMsg.class);
		arp.addMapping(Tags.TABLE_NAME, Tags.class);
		// 插件加载一直空指针
		me.add(new MCachePlugin());
		// 添加Quartz定时调度
		// me.add(new QuartzPlugin());
	}

	private boolean isDevMode() {
		String osName = System.getProperty("os.name"); // 电脑系统名称
		// 坑爹，这里用户名为null
		boolean is = StringKit.notBlank(osName) && osName.indexOf("Windows") != -1;
		if (logger.isErrorEnabled()) {
			logger.error("isDevMode=[" + is + "]");
		}

		return is;
	}

	/**
	 * 运行此 main 方法可以启动项目，此main方法可以放置在任意的Class类定义中，不一定要放于此
	 */
	public static void main(String[] args) {
		JFinal.start("WebContent", 80, "/", 10);
	}
}
